package com.denghq.projectbuilder.component.consul.config.configuration;

import com.ecwid.consul.v1.ConsulClient;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.cloud.consul.ConditionalOnConsulEnabled;
import org.springframework.cloud.endpoint.RefreshEndpoint;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;

@Configuration
@ConditionalOnConsulEnabled
@ConditionalOnProperty(
        name = {"spring.cloud.consul.config.enabled"},
        matchIfMissing = true
)
public class ConsulConfigAutoConfiguration {

    public static final String CONFIG_WATCH_TASK_SCHEDULER_NAME = "configWatchTaskScheduler";

    public ConsulConfigAutoConfiguration() {
    }

    @Configuration
    @ConditionalOnClass({RefreshEndpoint.class})
    protected static class ConsulRefreshConfiguration {
        protected ConsulRefreshConfiguration() {
        }

        @Bean
        @ConditionalOnProperty(
                name = {"spring.cloud.consul.config.watch.enabled"},
                matchIfMissing = true
        )
        @ConditionalOnMissingBean(ConsulConfigWatcher.class)
        public ConsulConfigWatcher configWatch(ConsulConfigProperties properties, ConsulConfigPropertySourceLocator locator, ConsulClient consul, @Qualifier(CONFIG_WATCH_TASK_SCHEDULER_NAME) TaskScheduler taskScheduler) {
            return new ConsulConfigWatcher(properties, consul, locator.getConfigDescriptorList(), taskScheduler);
        }

        @Bean(
                name = {CONFIG_WATCH_TASK_SCHEDULER_NAME}
        )
        @ConditionalOnProperty(
                name = {"com.denghq.component.consul.config.watch.enabled"},
                matchIfMissing = true
        )
        @ConditionalOnMissingBean(name = {CONFIG_WATCH_TASK_SCHEDULER_NAME})
        public TaskScheduler configWatchTaskScheduler() {
            return new ThreadPoolTaskScheduler();
        }
    }
}
